import Taro from "@tarojs/taro"
import lodash from "@/utils/lodash"
import { setUrlParams, verifyType, getCurrentPages } from '@/utils/utils'
import { USER_INFO, AUTH_TOKEN, SHARE_CODE, WECHAT_CODE_TO_SESSION_KEY, ACTIVITY_POPUP_TIME } from '@/config/storage'
import xfUtil from '@xfjs/xf-utils-vue'


/* ------------------------------------------------------- 全局变量 ------------------------------------------------------- */
/**
 * 写入全局变量
 * @param data 写入值（{ token: 'hello word' }）
 */
export function setGlobalData(data: Object) {
  const { globalData } = Taro.getApp()
  Object.keys(data).map(name => {
    globalData[name] = data[name]
  })
}

/**
 * 获取全局变量
 * @param name 字段名称
 */
export function getGlobalData(name?: string) {
  const { globalData } = Taro.getApp() || { globalData: {} }
  return (name ? globalData[name] : globalData)
}

/**
 *  追加购物车数量
 */
export function addGlobalCartCount() {
  const number = getGlobalCartCount() + 1
  setGlobalData({ cartCount: number })
  return number
}

/**
 *  获取购物车数量
 */
export function getGlobalCartCount() {
  return getGlobalData('cartCount') || 0
}

/**
 *  写入购物车
 */
export function setShopCartGlobal(list) {
  setGlobalData({ cartList: list })
}

/**
 *  获取购物车
 */
export function getShopCartGlobal() {
  return getGlobalData('cartList') || []
}

/**
 * 退出登录清除全局变量
 */
export function logout() {
  setUserTokenStorage('')
  Taro.removeStorage({ key: USER_INFO })
  Taro.removeStorage({ key: AUTH_TOKEN })
  Taro.removeStorage({ key: SHARE_CODE })
  Taro.removeStorage({ key: 'AUTH_ORIGINAL' })
  // setGlobalData({
  //   token: '',
  //   cartList: [],
  //   cartCount: 0
  // })
}

/**
 *  清空用户缓存
 */
export function clearUserStorage() {
  Taro.removeStorage({ key: USER_INFO })
  Taro.removeStorage({ key: AUTH_TOKEN })
  Taro.removeStorage({ key: SHARE_CODE })
  Taro.removeStorage({ key: ACTIVITY_POPUP_TIME })
  Taro.removeStorage({ key: WECHAT_CODE_TO_SESSION_KEY })
}

/* ------------------------------------------------------- 全局变量 ------------------------------------------------------- */



/* ------------------------------------------------------- 用户信息 ------------------------------------------------------- */
/**
 *  获取用户信息
 */
export function getUserInfoStorage() {
  const info = Taro.getStorageSync(USER_INFO)
  if (verifyType(info, 'Object')) {
    return info
  }
  return {}
}
/* ------------------------------------------------------- 用户信息 ------------------------------------------------------- */

/* ------------------------------------------------------- 用户登录状态 ------------------------------------------------------- */

/**
 * 验证用户是否登录
 * @param success 成功的回调函数
 * @param fail 失败的回调函数
 * @param complete 结束的回调函数（调用成功、失败都会执行）
 */
export function verifyUserLogin({ success, fail, complete }: any) {
  // const token = getGlobalData('token')
  const token = Taro.getStorageSync(AUTH_TOKEN)
  if (token) {
    success && success(token)
    complete && complete()
  } else {
    fail && fail()
    complete && complete()
  }
}

/* ------------------------------------------------------- 用户登录状态 ------------------------------------------------------- */




/* ------------------------------------------------------- 小程序配置 ------------------------------------------------------- */
/**
 *  写入小程序配置
 */
export function setAppConfig(list) {
  if (verifyType(list, 'Object')) {
    Taro.setStorageSync('USER_CONFIG', list)
  }
}

/**
 *  获取小程序配置
 */
export function getAppConfig(name?) {
  const storage = Taro.getStorageSync('USER_CONFIG') || {}
  return name ? storage[name] : storage
}



/**
 *  写入小程序配置
 */
export function setAppletConfig(config) {
  if (verifyType(config, 'Object')) {
    Taro.setStorageSync('APPLET_CONFIG', config)
  }
}

/**
 *  获取小程序配置
 */
export function getAppletAllConfig(name?) {
  const storage = Taro.getStorageSync('APPLET_CONFIG') || {}
  return name ? storage[name] : storage
}

/**
 *  获取小程序配置
 */
export function getAppletConfig(name?) {
  const config = getAppletAllConfig('indexAppConfig') || {}
  return name ? config[name] : config
}

/**
 *  获取拼团配置
 */
export function getPinkConfig(name?) {
  const config = getAppletAllConfig('pinkConfig') || {}
  return name ? config[name] : config
}

/**
 *  获取快递配置
 */
export function getFreightConfig(name?) {
  const config = getAppletAllConfig('freight') || {}
  return name ? config[name] : config
}

/* ------------------------------------------------------- 小程序配置 ------------------------------------------------------- */



/* ------------------------------------------------------- 活动配置 ------------------------------------------------------- */

/**
 *  获取活动时间
 */
export function getActivityTimeStorage(name?) {
  const info = Taro.getStorageSync(ACTIVITY_POPUP_TIME)
  const config = verifyType(info, 'Object') ? info : {}
  return (name ? config[name] : config)
}

/**
 *  写入活动时间
 */
export function setActivityTimeStorage(name: any, config: object) {
  if (verifyType(config, 'Object')) {
    const info = getActivityTimeStorage()
    Taro.setStorageSync(ACTIVITY_POPUP_TIME, { ...info, [name]: config })
  }
}

/* ------------------------------------------------------- 活动配置 ------------------------------------------------------- */



/* ------------------------------------------------------- 分享 code ------------------------------------------------------- */

/**
 * 获取小程序分享path
 */
export function getSharePath(path?, params?) {
  const page = getCurrentPages()
  const route = path ? path : lodash.cloneDeep(page.route)
  const options = params ? params : lodash.cloneDeep(page.options)
  const scene = Taro.getStorageSync(SHARE_CODE)
  scene && (options.scene = scene)
  return setUrlParams(route, options)
}

/* ------------------------------------------------------- 分享 code ------------------------------------------------------- */








/**
 * 获取 session 缓存
 * @param name
 */
export function getSessionStorage(name: string) {
  try {
    const val = sessionStorage.getItem(name)
    return val ? JSON.parse(val) : val
  } catch (e) {
    // console.log(e)
    console.log(`sessionStorage.getItem(${name}) 错误`)
  }
}

/**
 * 写入 session 缓存
 * @param name
 * @param data
 */
export function setSessionStorage(name: string, data: any) {
  try {
    return sessionStorage.setItem(name, JSON.stringify(data))
  } catch (e) {
    // console.log(e)
    console.log(`sessionStorage.setItem(${name}) 错误`)
  }
}

export function getBrand() {
  return getSessionStorage('AUTH_TOKEN_BRAND')
}

export function TotalScore() {
  return Number(Taro.getStorageSync(USER_INFO).totalScore)
}

export function goodsScore(score) {
  return xfUtil.gt(score, 0)
}




//  商品随机分页
let randomProduct: any = []

/**
 * 写入商品随机分页
 */
export function setRandomPage(list: any) {
  randomProduct = lodash.cloneDeep(list)
}

/**
 * 获取商品随机分页
 */
export function getRandomPage() {
  return lodash.cloneDeep(randomProduct)
}


export function getRandomPageNumber() {
  const list = lodash.cloneDeep(randomProduct)
  const key = Math.floor(Math.random() * list.length + 1) - 1
  const k = list[key]
  list.splice(key, 1)
  setRandomPage(list)
  return k
}













/* --------------------------------------------------- token --------------------------------------------------- */
//  商品随机分页
let userToken: any = ''

/**
 * 写入用户 token
 */
export function setUserTokenStorage(token: string) {
  userToken = lodash.cloneDeep(token)
}

/**
 * 获取用户 token
 */
export function getUserTokenStorage() {
  return lodash.cloneDeep(userToken)
}


/* --------------------------------------------------- address --------------------------------------------------- */

/**
 *  写入提交地址
 */
export function setReceiveAddress(config) {
  Taro.setStorageSync('RECEIVE_ADDRESS', config)
}

/**
 *  获取提交地址
 */
export function getReceiveAddress(name?) {
  const storage = Taro.getStorageSync('RECEIVE_ADDRESS') || {}
  return name ? storage[name] : storage
}

/* --------------------------------------------------- sourceId --------------------------------------------------- */

/**
 *  写入提交地址
 */
 export function setSourceId(config) {
  Taro.setStorageSync('SOURECID', config)
}

/**
 *  获取提交地址
 */
export function getSourceId(name?) {
  const storage = Taro.getStorageSync('SOURECID') || {}
  return name ? storage[name] : storage
}